# version 330 core

// 材质属性
struct Material {
    sampler2D diffuse;    // 漫反射光照(一般情况下环境光颜色都等于漫反射颜色)
    sampler2D specular;   // 镜面光照
    float     shininess;
};

// 光照属性
struct Light {
    vec3 position;   // 光源位置
    vec3 direction;  // 定向光, 指向光源
    float cutOff;
    float outerCutOff;

    vec3 ambient;    // 环境光照
    vec3 diffuse;    // 漫反射光照
    vec3 specular;   // 镜面光照

    float constant;
    float linear;
    float quadratic;
};

in vec2 texCoords;
in vec3 normal;
in vec3 fragPos;

out vec4 fragColor;

uniform vec3     u_viewPos;
uniform Material material;
uniform Light    light;

void main()
{
    vec3 lightDir = normalize(light.position - fragPos);
    float theta = dot(lightDir, normalize(-light.direction));
    float epsilon   = light.cutOff - light.outerCutOff;
    float intensity = clamp((theta - light.outerCutOff) / epsilon, 0.0, 1.0);

    // 环境光
    vec3 ambient = light.ambient * vec3(texture(material.diffuse, texCoords));
    
    // 漫反射
    vec3 norm = normalize(normal);
    float diff = max(dot(norm, lightDir), 0.0);
    vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, texCoords));
    
    // 镜面光
    vec3 viewDir = normalize(u_viewPos - fragPos);
    vec3 reflectDir = reflect(-lightDir, norm);
    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);
    vec3 specular = light.specular * spec * vec3(texture(material.specular, texCoords));

    float distance    = length(light.position - fragPos);
    float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance));
    
    diffuse  *= intensity;
    specular *= intensity;

    ambient  *= attenuation;
    diffuse  *= attenuation;
    specular *= attenuation;
    vec3 result = ambient + diffuse + specular;
    fragColor = vec4(result, 1.0);
}